package com.example.fund.util;

import java.util.List;

public class MathUtil {

	/**
	 * STDEV函数，用于估算基于样本的标准偏差。标准偏差判断数值相对于平均值的离散程度。
	 * @param
	 * @return
	 */
	public static double stdev(List<Double> valList){
		double[] vals = new double[valList.size()];
		for(int i=0;i<valList.size();i++)
		{
			vals[i] = valList.get(i);
		}
		 
		return stdev(vals);
	}
	
	/**
	 * STDEV函数，用于估算基于样本的标准偏差。标准偏差判断数值相对于平均值的离散程度。
	 * @param vals
	 * @return
	 */
	public static double stdev(double[] vals){
		if(vals.length==0 || vals.length==1)
		{
			return 0;
		}
	    double rval = 0;  
	    double avg = average(vals);  
	    for (int i = 0; i < vals.length; i++) {  
	        rval += Math.pow((vals[i] - avg), 2);  
	    }  
	    rval /= vals.length-1;  
	    rval = Math.sqrt(rval);  
	    return rval;  
	}
	
	public static double average(double[] vals)
	{
		double sum = 0;
		for(int i=0;i<vals.length;i++)
		{
			sum+=vals[i];
		}
		
		return sum/vals.length;
	}
	
	public static void main(String[] args) {
		int l = 2;
		double[] data = new double[l];
		for(int i=0;i<l;i++)
		{
			double s = Math.random();
			data[i] = s;
			System.out.println(s);
		}
		System.out.println("stdev:"+MathUtil.stdev(data));
	}
}
